package com.example.previewpicture.nine.adapter;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.previewpicture.ResourceTable;
import com.example.previewpicture.app.GlideBitmapTransformation;
import com.example.previewpicture.bean.UserViewInfo;
import com.example.previewpicture.nine.entity.Post;
import com.jaeger.ninegridimageview.ItemImageClickListener;
import com.jaeger.ninegridimageview.NineGridImageView;
import com.jaeger.ninegridimageview.NineGridImageViewAdapter;
import com.previewlibrary.GPreviewBuilder;

import com.previewlibrary.utils.Toast;
import ohos.aafwk.ability.Ability;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.utils.Rect;
import ohos.app.Context;

import org.jetbrains.annotations.Nullable;

import uk.co.senab2.photoview2.log.LogManager;

import java.util.List;

/**
 * PostAdapter.
 *
 * @author author
 * @version version
 */
public class PostAdapter extends BaseItemProvider {
    private List<Post> mPostList;
    private Context mContext;

    public PostAdapter(Context context, List<Post> postList) {
        this.mContext = context;
        this.mPostList = postList;
    }

    @Override
    public int getCount() {
        return mPostList != null ? mPostList.size() : 0;
    }

    @Override
    public Object getItem(int i) {
        return mPostList != null ? mPostList.get(i) : null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        ViewHolder viewHolde = null;
        if (component == null) {
            component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_item_post_grid_style, null, false);
            viewHolde = new ViewHolder(component);
            component.setTag(viewHolde);
        } else {
            viewHolde = (ViewHolder) component.getTag();
        }
        viewHolde.bind(mPostList.get(position));


        return component;
    }

    class ViewHolder {
        Component itemView;

        Text mTvContent;

        NineGridImageView mNglContent;

        private NineGridImageViewAdapter<UserViewInfo> mAdapter = new NineGridImageViewAdapter<UserViewInfo>() {
            @Override
            protected void onDisplayImage(Context context, Image imageView, UserViewInfo s) {
                Glide.with(context)
                        .load(s.getUrl())
                        .apply(RequestOptions.bitmapTransform(new GlideBitmapTransformation())
                                .error(ResourceTable.Media_ic_default_image))
                        .listener(new RequestListener<Element>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Element> target, boolean b) {
                                imageView.setPixelMap(ResourceTable.Media_ic_default_image);
                                return true;
                            }

                            @Override
                            public boolean onResourceReady(Element element, Object o, Target<Element> target, DataSource dataSource, boolean b) {
                                return false;
                            }
                        })
                        .into(imageView);
            }

            @Override
            protected Image generateImageView(Context context) {
                return super.generateImageView(context);
            }

            @Override
            protected void onItemImageClick(Context context, Image imageView, int index, List<UserViewInfo> list) {
            }
        };


        public ViewHolder(Component component) {
            itemView = component;
            mTvContent = (Text) component.findComponentById(ResourceTable.Id_tv_content);
            mNglContent = (NineGridImageView) component.findComponentById(ResourceTable.Id_ngl_images);
            mNglContent.setAdapter(mAdapter);
            mNglContent.setItemImageClickListener(new ItemImageClickListener<UserViewInfo>() {
                @Override
                public void onItemImageClick(Context context, Image imageView, int index, List<UserViewInfo> list) {
                    computeBoundsBackward(list);//组成数据
                    GPreviewBuilder.from((Ability) context)
                            .setData(list)
                            .setIsScale(true)
                            .setCurrentIndex(index)
                            .setType(GPreviewBuilder.IndicatorType.Dot)
                            .start();//启动
                }
            });
        }

        private void computeBoundsBackward(List<UserViewInfo> list) {
            for (int i = 0; i < mNglContent.getChildCount(); i++) {
                Component itemView = mNglContent.getComponentAt(i);
                Rect bounds = new Rect();
                if (itemView != null) {
                    Image thumbView = (Image) itemView;
                    thumbView.getSelfVisibleRect(bounds);
                    int width = bounds.getWidth();
                    int height = bounds.getHeight();
                    int[] locationOnScreen = thumbView.getLocationOnScreen();
                    int left = locationOnScreen[0];
                    int top = locationOnScreen[1];
                    bounds.set(left, top, left + width, top + height);
                }
                list.get(i).setBounds(bounds);
                list.get(i).setUrl(list.get(i).getUrl());
            }
        }

        public void bind(Post post) {
            mNglContent.setImagesData(post.getImgUrlList());
            mTvContent.setText(post.getContent());
            LogManager.getLogger().d("jaeger", "九宫格高度: " + mNglContent.getEstimatedHeight());
            LogManager.getLogger().d("jaeger", "item 高度: " + itemView.getEstimatedHeight());
        }
    }

}
